#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct ListNode 
{
	int val;
	struct ListNode* next;
};

struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode* prev = NULL, * cur = head;
    while (cur)
    {
        if (cur->val == val)
        {
            if (prev == NULL)
            {
                cur = head->next;
                free(head);
                head = cur;
            }
            else
            {
                prev->next = cur->next;
                free(cur);
                cur = prev->next;
            }
        }
        else
        {
            prev = cur;
            cur = cur->next;
        }
    }
    return head;
}

struct ListNode* removeElements_1(struct ListNode* head, int val)
{
    struct ListNode* newhead = NULL, * tail = NULL, * cur = head;
    while (cur)
    {
        if (cur->val != val)
        {
            if (tail == NULL)
            {
                newhead = cur;
                tail = cur;
            }
            else
            {
                tail->next = cur;
                tail = cur;
            }
            cur = cur->next;
            tail->next = NULL;
        }
        else
        {
            struct ListNode* del = cur;
            cur = cur->next;
            free(del);
        }
    }
    return newhead;
}
int main()
{
	struct ListNode* p1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(p1);
	struct ListNode* p2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(p2);
	struct ListNode* p3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(p3);
	struct ListNode* p4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(p4);
	struct ListNode* p5 = (struct ListNode*)malloc(sizeof(struct ListNode));
    assert(p5);

	p1->next = p2;
	p2->next = p3;
	p3->next = p4;
	p4->next = p5;
	p1->val = 1;
	p2->val = 2;
	p3->val = 3;
	p4->val = 4;
	p5->val = 5;

    struct ListNode* node=removeElements(p1, 3);
	return 0;
}